import { useLocalStorage } from "@/hooks/localStorage/useLocalStorage";
import axios, { AxiosRequestConfig } from "axios";
import NProgress from "nprogress";

const baseURL = import.meta.env.VITE_APP_BASE_URL as string;
const { getStorageItem } = useLocalStorage()

// 设置请求头和请求路径
axios.defaults.baseURL = baseURL;
axios.defaults.timeout = 10000;
axios.defaults.headers.post["Content-Type"] = "application/json;charset=UTF-8";
axios.defaults.withCredentials = true;
axios.interceptors.request.use(
  (config): AxiosRequestConfig<any> => {
    return config;
  },
  (error) => {
    return error;
  }
);
// 响应拦截
axios.interceptors.response.use((res) => {
  if (res.data.code === 111) {
    // token过期操作
  }
  return res;
});

interface ResType<T> {
  code: number;
  data: T;
  result: T;
  message: string;
  err?: string;
  [name: string]: any; //本不想加这一行的，可惜接口实在太不规范，没办法
}
interface Http {
  get<T>(url: string, params?: unknown, cache?: boolean): Promise<ResType<T>>;
  post<T>(url: string, params?: unknown, cache?: boolean): Promise<ResType<T>>;
  upload<T>(url: string, params: unknown): Promise<ResType<T>>;
  download(url: string): void;
}

const http: Http = {
  //cache为是否使用缓存.若不使用缓存，则在url上添加时间戳
  get(url, params, cache = false) {
    return new Promise((resolve, reject) => {
      NProgress.start();
      if (!cache) url += `?t=${new Date().getTime()}`;
      const token = getStorageItem('token')
      if (token !== "") url += `&cookie=${encodeURIComponent(token)}`;
      axios
        .get(url, { params })
        .then((res) => {
          NProgress.done();
          resolve(res.data);
        })
        .catch((err) => {
          NProgress.done();
          reject(err.data);
        });
    });
  },
  post(url, params, cache = false) {
    //cache为是否使用缓存.若不使用缓存，则在url上添加时间戳
    return new Promise((resolve, reject) => {
      NProgress.start();
      if (!cache) url += `?t=${new Date().getTime()}`;
      const token = getStorageItem('token')
      // @ts-ignore
      if (token !== "" && params && typeof params === "object") params.cookie = token;
      axios
        .post(url, JSON.stringify(params))
        .then((res) => {
          NProgress.done();
          resolve(res.data);
        })
        .catch((err) => {
          NProgress.done();
          reject(err.data);
        });
    });
  },
  upload(url, file) {
    return new Promise((resolve, reject) => {
      NProgress.start();
      axios
        .post(url, file, {
          headers: { "Content-Type": "multipart/form-data" },
        })
        .then((res) => {
          NProgress.done();
          resolve(res.data);
        })
        .catch((err) => {
          NProgress.done();
          reject(err.data);
        });
    });
  },
  download(url) {
    const iframe = document.createElement("iframe");
    iframe.style.display = "none";
    iframe.src = url;
    iframe.onload = function () {
      document.body.removeChild(iframe);
    };
    document.body.appendChild(iframe);
  },
};
export default http;
